<!DOCTYPE HTML>
<html lang="zh-CN">
    <!-- shw2018 洪卫  modify 2019.08.15-->



<head><meta name="generator" content="Hexo 3.9.0">
    <meta charset="utf-8">
    <meta name="keywords" content="数据结构与算法13—查找, 计算机 数据 运营">
    <meta name="baidu-site-verification" content="fmlEuI34ir">
    <meta name="google-site-verification" content="KeoTn_OFy4ndJwXNmm2gMeQfPhd7alqE9vQDwI32KCY">
    <meta name="description" content="一、基本概念
查找就是在数据集中找出一个“特定元素”。
查找表是由同一类型的数据元素(或记录)构成的集合。
查找表是一种以集合为逻辑结构、以查找为核心的数据结构。

关键字有时候我们需要指定某数据项的值来查找，这就用到了关键字。关键字是数据">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>数据结构与算法13—查找 | hisen</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.bootcss.com/materialize/1.0.0/css/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.bootcss.com/aos/3.0.0-beta.6/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.bootcss.com/lightgallery/1.6.12/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">
    
    <style type="text/css">
        
            
            code[class*="language-"],
            pre[class*="language-"] {
                white-space: pre !important;
            }

        
    </style>

    <script src="https://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
    <script src="https://sdk.jinrishici.com/v2/browser/jinrishici.js" charset="utf-8"></script>
    
    <script>
        var _hmt = _hmt || [];
        (function () {
            var hm = document.createElement("script");
            hm.src = "https://hm.baidu.com/hm.js?46e79e71af0709a5b9106bf20cecc493";
            var s = document.getElementsByTagName("script")[0];
            s.parentNode.insertBefore(hm, s);
        })();
    </script>

    
    
        <script>
            (function(){
                var bp = document.createElement('script');
                var curProtocol = window.location.protocol.split(':')[0];
                if (curProtocol === 'https') {
                    bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
                }
                else {
                    bp.src = 'http://push.zhanzhang.baidu.com/push.js';
                }
                var s = document.getElementsByTagName("script")[0];
                s.parentNode.insertBefore(bp, s);
            })();
        </script>
    

<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>

    <body>

        <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">hisen</span>
                </a>
            </div>
            


<!-- <a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fa fa-navicon"></i></a>
<ul class="right">
    
    <li class="hide-on-med-and-down">
        <a href="/" class="waves-effect waves-light">
            
            <i class="fa fa-home"></i>
            
            <span>首页</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/tags" class="waves-effect waves-light">
            
            <i class="fa fa-tags"></i>
            
            <span>标签</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/categories" class="waves-effect waves-light">
            
            <i class="fa fa-bookmark"></i>
            
            <span>分类</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/archives" class="waves-effect waves-light">
            
            <i class="fa fa-archive"></i>
            
            <span>归档</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/about" class="waves-effect waves-light">
            
            <i class="fa fa-user-circle-o"></i>
            
            <span>关于我</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/contact" class="waves-effect waves-light">
            
            <i class="fa fa-envelope"></i>
            
            <span>留言板</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/friends" class="waves-effect waves-light">
            
            <i class="fa fa-address-book"></i>
            
            <span>友情链接</span>
        </a>
    </li>
    
    <li>
        <a href="#searchModal" class="modal-trigger waves-effect waves-light">
            <i id="searchIcon" class="fa fa-search" title="搜索"></i>
        </a>
    </li>
</ul> -->

<!-- 支持二级菜单特性 洪卫 shw2018 modify 2019.09.17  -->
<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fa fa-navicon"></i></a>
<ul class="right nav-menu">
    
      <li class="hide-on-med-and-down nav-item" >

        
            <a href="/" class="waves-effect waves-light">
              
                <i class="fa fa-home"></i>
              
              <span>首页</span>
            </a>

            
      </li>
    
      <li class="hide-on-med-and-down nav-item" >

        
            <a href="/tags" class="waves-effect waves-light">
              
                <i class="fa fa-tags"></i>
              
              <span>标签</span>
            </a>

            
      </li>
    
      <li class="hide-on-med-and-down nav-item" >

        
            <a href="/categories" class="waves-effect waves-light">
              
                <i class="fa fa-bookmark"></i>
              
              <span>分类</span>
            </a>

            
      </li>
    
      <li class="hide-on-med-and-down nav-item" >

        
            <a href="/archives" class="waves-effect waves-light">
              
                <i class="fa fa-archive"></i>
              
              <span>归档</span>
            </a>

            
      </li>
    
      <li class="hide-on-med-and-down nav-item" >

        
            <a href="/about" class="waves-effect waves-light">
              
                <i class="fa fa-user-circle-o"></i>
              
              <span>关于我</span>
            </a>

            
      </li>
    
      <li class="hide-on-med-and-down nav-item" >

        
            <a href="/contact" class="waves-effect waves-light">
              
                <i class="fa fa-envelope"></i>
              
              <span>留言板</span>
            </a>

            
      </li>
    
      <li class="hide-on-med-and-down nav-item" >

        
            <a href="/friends" class="waves-effect waves-light">
              
                <i class="fa fa-address-book"></i>
              
              <span>友情链接</span>
            </a>

            
      </li>
    

    <li>
        <a href="#searchModal" class="modal-trigger waves-effect waves-light">
            <i id="searchIcon" class="fa fa-search" title="搜索"></i>
        </a>
    </li>

</ul>

<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">hisen</div>
        <div class="logo-desc">
            
            hisen Lee | 亦小海
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li>
            <a href="/" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-home"></i>
                
                首页
            </a>
        </li>
        
        <li>
            <a href="/tags" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-tags"></i>
                
                标签
            </a>
        </li>
        
        <li>
            <a href="/categories" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-bookmark"></i>
                
                分类
            </a>
        </li>
        
        <li>
            <a href="/archives" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-archive"></i>
                
                归档
            </a>
        </li>
        
        <li>
            <a href="/about" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-user-circle-o"></i>
                
                关于我
            </a>
        </li>
        
        <li>
            <a href="/contact" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-envelope"></i>
                
                留言板
            </a>
        </li>
        
        <li>
            <a href="/friends" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-address-book"></i>
                
                友情链接
            </a>
        </li>
        
        
    </ul>

   
   
<!-- 支持二级菜单特性 洪卫 shw2018 modify 2019.09.17  -->
<!-- <ul class="menu-list mobile-menu-list">
    
        <li class="m-nav-item">
                
                    <a href="/" class="waves-effect waves-light">
                        
                        <i class="fa fa-fw fa-home"></i>
                        
                        首页
                    </a>
              
            </li>
        
        <li class="m-nav-item">
                
                    <a href="/tags" class="waves-effect waves-light">
                        
                        <i class="fa fa-fw fa-tags"></i>
                        
                        标签
                    </a>
              
            </li>
        
        <li class="m-nav-item">
                
                    <a href="/categories" class="waves-effect waves-light">
                        
                        <i class="fa fa-fw fa-bookmark"></i>
                        
                        分类
                    </a>
              
            </li>
        
        <li class="m-nav-item">
                
                    <a href="/archives" class="waves-effect waves-light">
                        
                        <i class="fa fa-fw fa-archive"></i>
                        
                        归档
                    </a>
              
            </li>
        
        <li class="m-nav-item">
                
                    <a href="/about" class="waves-effect waves-light">
                        
                        <i class="fa fa-fw fa-user-circle-o"></i>
                        
                        关于我
                    </a>
              
            </li>
        
        <li class="m-nav-item">
                
                    <a href="/contact" class="waves-effect waves-light">
                        
                        <i class="fa fa-fw fa-envelope"></i>
                        
                        留言板
                    </a>
              
            </li>
        
        <li class="m-nav-item">
                
                    <a href="/friends" class="waves-effect waves-light">
                        
                        <i class="fa fa-fw fa-address-book"></i>
                        
                        友情链接
                    </a>
              
            </li>
        

        
    </ul> -->

</div>

        </div>

        
    </nav>

</header>

        
<script src="/libs/cryptojs/crypto-js.min.js"></script>
<script>
    (function() {
        let pwd = '';
        if (pwd && pwd.length > 0) {
            if (pwd !== CryptoJS.SHA256(prompt('请输入访问本文章的密码')).toString(CryptoJS.enc.Hex)) {
                alert('密码错误，将返回主页！');
                location.href = '/';
            }
        }
    })();
</script>




<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/banner/8.jpg')">
    <div class="container">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <div class="description center-align post-title">
                        数据结构与算法13—查找
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>



<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 20px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- shw2018 洪卫  modify 2019.08.15-->
<!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/数据结构/" target="_blank">
                                <span class="chip bg-color">数据结构</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fa fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/数据结构/" class="post-category" target="_blank">
                                数据结构
                            </a>
                        
                    </div>
                    
                </div>
            </div>
            
            <div class="post-info">
                <div class="post-date info-break-policy">
                    <i class="fa fa-calendar-minus-o fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2019-02-14
                </div>

                <div class="post-author info-break-policy">
                    <i class="fa fa-user-o fa-fw"></i>作者:&nbsp;&nbsp;
                    
                        hisen
                    
                </div>

                
                    
                    <div class="info-break-policy">
                        <i class="fa fa-file-word-o fa-fw"></i>文章字数:&nbsp;&nbsp;
                        3.6k
                    </div>
                    

                    
                    <div class="info-break-policy">
                        <i class="fa fa-clock-o fa-fw"></i>阅读时长:&nbsp;&nbsp;
                        13 分
                    </div>
                    
                
                
                
                        <span id="busuanzi_container_site_pv" style='display:none'></span>
                        <i class="fa fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv" ></span>
    
                

            </div>
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <h2 id="一、基本概念"><a href="#一、基本概念" class="headerlink" title="一、基本概念"></a>一、基本概念</h2><ul>
<li>查找就是在数据集中找出一个“特定元素”。</li>
<li>查找表是由同一类型的数据元素(或记录)构成的集合。</li>
<li>查找表是一种以集合为逻辑结构、以查找为核心的数据结构。</li>
</ul>
<p><strong>关键字</strong><br>有时候我们需要指定某数据项的值来查找，这就用到了关键字。<br>关键字是数据元素中某个数据项的值，用以标识一个数据元素。<br>若此关键字可以识别唯一的一个记录，则称之谓“主关键字”；若此关键字能识别若干记录，则称之谓“次关键字”。</p>
<p>例：<br><img src="https://cdn.jsdelivr.net/gh/shw2018/cdn@1.0/sakura/img/loader/orange.progress-bar-stripe-loader.svg" data-original="/medias/img/sjjg/3381152599.png" alt=" "></p>
<ul>
<li><strong>对查找表经常进行的操作</strong>:    </li>
</ul>
<p>1）查询某个“特定的”数据元素是否在查找表中；<br>2）检索某个“特定的”数据元素的各种属性；<br>3）在查找表中插入一个数据元素；<br>4）从查找表中删去某个数据元素。</p>
<ul>
<li><strong>查找表可分为两类</strong>:</li>
</ul>
<p><strong>静态查找</strong>：仅作查询和检索操作。查找前后查找表未发生变化。<br><strong>动态查找</strong>：在查询之后，将 “不在查找表中”的数据元素插入到查找表中；或者，从查找表中删除“在查找表中”的数据元素。 查找前后查找表发生了变化。</p>
<p>采用何种查找方法，取决于使用哪种数据结构来表示“查找表”。即表中记录是按何种方式组织的，根据不同的数据结构采用不同的查找方法。</p>
<ul>
<li><strong>平均查找长度</strong>:<br>查找算法中的基本运算是记录的关键字与给定值所进行的比较。其执行时间通常取决于关键字的比较次数，也称为<strong>平均查找长度ASL</strong> 。<br>ASL是衡量一个查找算法优劣的重要指标。<br>定义为：<br><img src="https://cdn.jsdelivr.net/gh/shw2018/cdn@1.0/sakura/img/loader/orange.progress-bar-stripe-loader.svg" data-original="/medias/img/sjjg/3454176683.png" alt=" "></li>
</ul>
<p>n 是查找表中记录的个数<br>Pi 是查找第i个记录的概率<br>Ci 是找到第i个记录所需进行的比较次数。</p>
<p><strong>静态查找</strong><br>线性表查找属于静态查找，是将查找表视为一个线性表，将其顺序或链式存储，再进行查找，因此查找思想较为简单，效率不高。如果查找表中的数据元素有一定的规律（如按关键字有序），可以利用这些信息获得较好的查找效率。</p>
<h3 id="二、顺序查找"><a href="#二、顺序查找" class="headerlink" title="二、顺序查找"></a>二、顺序查找</h3><p>即数据存储在顺序表中，然后逐项查找元素。<br>实现：</p>
<pre class=" language-c"><code class="language-c"><span class="token macro property">#<span class="token directive keyword">define</span>  MAXNUM  100    </span><span class="token comment" spellcheck="true">/*查找表的容量*/</span>
<span class="token keyword">typedef</span>  <span class="token keyword">int</span>  KeyType<span class="token punctuation">;</span>
<span class="token keyword">typedef</span>   <span class="token keyword">struct</span><span class="token punctuation">{</span>
    KeyType  key<span class="token punctuation">;</span>     <span class="token comment" spellcheck="true">/*关键字字段*/</span>
<span class="token punctuation">}</span>DataType<span class="token punctuation">;</span>
<span class="token keyword">typedef</span> <span class="token keyword">struct</span><span class="token punctuation">{</span>
    DataType  data<span class="token punctuation">[</span>MAXNUM<span class="token punctuation">]</span><span class="token punctuation">;</span>   <span class="token comment" spellcheck="true">/*存储空间*/</span>
    <span class="token keyword">int</span> n<span class="token punctuation">;</span>  <span class="token comment" spellcheck="true">/*元素个数*/</span>
<span class="token punctuation">}</span>SeqList<span class="token punctuation">;</span></code></pre>
<pre class=" language-c"><code class="language-c"><span class="token keyword">int</span> <span class="token function">Seq_Search_1</span> <span class="token punctuation">(</span>SeqList list<span class="token punctuation">,</span> KeyType kx<span class="token punctuation">)</span>
<span class="token punctuation">{</span><span class="token comment" spellcheck="true">/*数据存放在list.data[1] 至list.data[n]中，在表list中查找关键字为kx的数据元素*/</span>
<span class="token comment" spellcheck="true">/*若找到返回该元素在查找表中的位置，否则返回0*/</span>
    <span class="token keyword">int</span> i<span class="token operator">=</span><span class="token number">1</span><span class="token punctuation">;</span>
    <span class="token keyword">while</span><span class="token punctuation">(</span>i<span class="token operator">&lt;=</span>list<span class="token punctuation">.</span>n <span class="token operator">&amp;&amp;</span> list<span class="token punctuation">.</span>data<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">.</span>key<span class="token operator">!=</span> kx <span class="token punctuation">)</span> 
        i<span class="token operator">++</span><span class="token punctuation">;</span>   <span class="token comment" spellcheck="true">/* 从表头端向后查找 */</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>i<span class="token operator">></span>list<span class="token punctuation">.</span>n<span class="token punctuation">)</span> 
        <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span>
    <span class="token keyword">else</span>  
        <span class="token keyword">return</span>  i<span class="token punctuation">;</span> 
<span class="token punctuation">}</span></code></pre>
<p>加监视哨后的顺序查找：</p>
<pre class=" language-c"><code class="language-c"><span class="token keyword">int</span> <span class="token function">Seq_Search_2</span><span class="token punctuation">(</span>SeqList list<span class="token punctuation">,</span> KeyType kx<span class="token punctuation">)</span>
<span class="token punctuation">{</span> <span class="token comment" spellcheck="true">/*数据存放在list.data[1] 至list.data[n]中，在表list中查找关键字为kx的数据元素*/</span>
<span class="token comment" spellcheck="true">/*若找到返回该元素在查找表中的位置，否则返回0 */</span>
    <span class="token keyword">int</span> i<span class="token punctuation">;</span>
    list<span class="token punctuation">.</span>data<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">.</span>key<span class="token operator">=</span>kx<span class="token punctuation">;</span>    
    i<span class="token operator">=</span>list<span class="token punctuation">.</span>n<span class="token punctuation">;</span>
    <span class="token keyword">while</span><span class="token punctuation">(</span>list<span class="token punctuation">.</span>data<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">.</span>key<span class="token operator">!=</span> kx <span class="token punctuation">)</span> 
        i<span class="token operator">--</span><span class="token punctuation">;</span>  <span class="token comment" spellcheck="true">/* 从表尾端向前查找 */</span>
    <span class="token keyword">return</span> i<span class="token punctuation">;</span>
<span class="token punctuation">}</span> </code></pre>
<p>比较次数减少了，效率提高。</p>
<p><strong>顺序表上的顺序查找的性能分析</strong><br>对于n个元素的查找表，若查找的是表中第i个记录时，需进行n-i+1次关键字比较，即ci=n-i+1。<br>设查找每个元素的概率相等。 查找成功时，顺序查找的平均查找长度为：<br><img src="https://cdn.jsdelivr.net/gh/shw2018/cdn@1.0/sakura/img/loader/orange.progress-bar-stripe-loader.svg" data-original="/medias/img/sjjg/3178881732.png" alt=" "></p>
<p>查找不成功时，表中每个关键字都要比较一次，直到监视哨，因此关键字的比较次数总是n+1次，显然时间复杂度为O(n)。</p>
<p><strong>顺序查找的特点</strong></p>
<ul>
<li>顺序查找的优点是算法简单，对表中数据元素的存储方式、是否按关键字有序均无要求；</li>
<li>缺点是平均查找长度较大，效率低，当n很大时，不宜采用顺序查找。<br>为了提高查找效率，查找表中的数据存放需依据查找概率越高，使其比较次数越少；查找概率越低，比较次数可相对较多的原则来存储数据元素。</li>
</ul>
<p><strong>有序表查找</strong></p>
<ul>
<li>有序表是指查找表中的元素按关键字大小有序存储。</li>
<li>如果查找表采用顺序结构存储且按关键字有序，那么查找时可采用效率较高的折半查找算法实现。</li>
</ul>
<h3 id="三、二分查找（折半查找）"><a href="#三、二分查找（折半查找）" class="headerlink" title="三、二分查找（折半查找）"></a>三、二分查找（折半查找）</h3><p><strong>折半查找的思想为：</strong><br>在有序表中，取中间元素作为比较对象，若给定值与中间元素的关键字相等，则查找成功；若给定值小于中间元素的关键字，则在中间元素的左半区继续查找；若给定值大于中间元素的关键字，则在中间元素的右半区继续查找。不断重复上述查找过程，直到查找成功，或所查找的区域无数据元素，查找失败。</p>
<p>算法实现：</p>
<pre class=" language-c"><code class="language-c"><span class="token keyword">int</span> <span class="token function">Binary_Search</span><span class="token punctuation">(</span>SeqList list<span class="token punctuation">,</span> KeyType kx<span class="token punctuation">)</span>
<span class="token punctuation">{</span> <span class="token comment" spellcheck="true">/*数据存放在list.data[1] 至list.data[n]中，在表list中查找关键字为kx的数据元素*/</span>  
<span class="token comment" spellcheck="true">/*若找到返回该元素在表中的位置，否则返回0  */</span>
  <span class="token keyword">int</span> mid<span class="token punctuation">,</span>low<span class="token operator">=</span><span class="token number">1</span><span class="token punctuation">,</span> high<span class="token operator">=</span>list<span class="token punctuation">.</span>n<span class="token punctuation">;</span>   <span class="token comment" spellcheck="true">/*设置初始区间 */</span>
  <span class="token keyword">while</span><span class="token punctuation">(</span>low<span class="token operator">&lt;=</span>high<span class="token punctuation">)</span> <span class="token punctuation">{</span>   <span class="token comment" spellcheck="true">/*当查找区间非空*/</span>
      mid<span class="token operator">=</span><span class="token punctuation">(</span>low<span class="token operator">+</span>high<span class="token punctuation">)</span><span class="token operator">/</span><span class="token number">2</span><span class="token punctuation">;</span>  <span class="token comment" spellcheck="true">/*取区间中点 */</span>
      <span class="token keyword">if</span><span class="token punctuation">(</span>kx<span class="token operator">==</span>list<span class="token punctuation">.</span>data<span class="token punctuation">[</span>mid<span class="token punctuation">]</span><span class="token punctuation">.</span>key<span class="token punctuation">)</span> 
          <span class="token keyword">return</span> mid<span class="token punctuation">;</span>  <span class="token comment" spellcheck="true">/* 查找成功，返回mid */</span>
      <span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span>kx<span class="token operator">&lt;</span>list<span class="token punctuation">.</span>data<span class="token punctuation">[</span>mid<span class="token punctuation">]</span><span class="token punctuation">.</span>key<span class="token punctuation">)</span> 
          high<span class="token operator">=</span>mid<span class="token number">-1</span><span class="token punctuation">;</span>   <span class="token comment" spellcheck="true">/* 调整到左半区 */</span>
      <span class="token keyword">else</span> low<span class="token operator">=</span>mid<span class="token operator">+</span><span class="token number">1</span><span class="token punctuation">;</span>     <span class="token comment" spellcheck="true">/* 调整到右半区 */</span>   
  <span class="token punctuation">}</span>
  <span class="token keyword">return</span>  <span class="token number">0</span><span class="token punctuation">;</span>     <span class="token comment" spellcheck="true">/* 查找失败，返回0 */</span>
<span class="token punctuation">}</span></code></pre>
<p>折半查找的平均查找长度可用判定树来分析<br>先看一个具体的情况，假设：n=11<br><img src="https://cdn.jsdelivr.net/gh/shw2018/cdn@1.0/sakura/img/loader/orange.progress-bar-stripe-loader.svg" data-original="/medias/img/sjjg/3417493539.png" alt=" "></p>
<p><strong>二分查找的效率（ASL）</strong></p>
<p>1次比较就查找成功的元素有1个（2<sup>0</sup>），即中间值；<br>2次比较就查找成功的元素有2个（2<sup>1</sup>），即1/4处（或3/4）处；<br>3次比较就查找成功的元素有4个（2<sup>2</sup>），即1/8处（或3/8）处…<br>4次比较就查找成功的元素有8个（2<sup>3</sup>），即1/16处（或3/16）处…<br>……<br>则第h次比较时查找成功的元素会有（2<sup>h-1</sup>）个；<br>为方便起见，假设表中全部n个元素＝ 2<sup>h</sup>-1个，此时就不讨论第m次比较后还有剩余元素的情况了。<br><img src="https://cdn.jsdelivr.net/gh/shw2018/cdn@1.0/sakura/img/loader/orange.progress-bar-stripe-loader.svg" data-original="/medias/img/sjjg/3155597207.png" alt=" "></p>
<p>以含n个结点的满二叉树为例(n=2h-1),设查找概率相等,则二分查找的平均查找长度为：<br><img src="https://cdn.jsdelivr.net/gh/shw2018/cdn@1.0/sakura/img/loader/orange.progress-bar-stripe-loader.svg" data-original="/medias/img/sjjg/3951389407.png" alt=" "></p>
<p>最坏情况下,关键字比较次数为log2(n+1)，期望时间复杂度为O(log2n)</p>
<p>折半查找的前提条件是需要有序表顺序存储，对于静态查找表，一次排序后不再发生变化，折半查找能得到不错的效率。但对于需要频繁执行插入或删除操作的数据集来说，维护有序的排序会带来不小的工作量，那就不建议使用。</p>
<h3 id="顺序查找与二分查找的比较"><a href="#顺序查找与二分查找的比较" class="headerlink" title="顺序查找与二分查找的比较"></a>顺序查找与二分查找的比较</h3><p><strong>顺序查找：</strong><br>优点：算法简单，对数据特性无要求；<br>缺点：ASL大，效率低。<br><strong>二分查找：</strong><br>优点：查找速度快，效率高；<br>缺点：需在有序表上进行，且只限于顺序存储。</p>
<h3 id="四、插值查找"><a href="#四、插值查找" class="headerlink" title="四、插值查找"></a>四、插值查找</h3><p>在介绍插值查找之前，首先考虑一个新问题，为什么上述算法一定要是折半，而不是折四分之一或者折更多呢？<br>打个比方，在英文字典里面查“apple”，你下意识翻开字典是翻前面的书页还是后面的书页呢？如果再让你查“zoo”，你又怎么查？很显然，这里绝对不会是从中农间开始查起，而是有一定目的的往前或往后翻。<br>同样的，比如要在取值范围1~10000之间100个元素从小到大均匀分布的数组中查找5，我们自然会从数组下标较小的开始查找。<br>经过上面的分析，折半查找这种查找方式，不是自适应的（也就是一直保持分半的）。二分查找中查找点计算如下：<br><code>mid=(low+high)/2</code><br>即<br><code>mid=low+(high−low)/2</code><br>通过类比，我们可以将查找的点改进为如下：<br><img src="https://cdn.jsdelivr.net/gh/shw2018/cdn@1.0/sakura/img/loader/orange.progress-bar-stripe-loader.svg" data-original="/medias/img/sjjg/2455306463.png" alt=" "></p>
<p>也就是将上述的比例参数1/2改进为自适应的，根据关键字在整个有序表中所处的位置，让mid值的变化更靠近关键字key，这样也就间接地减少了比较次数。</p>
<p><strong>基本思想</strong>：基于二分查找算法，将查找点的选择改进为自适应选择，可以提高查找效率。当然，插值查找也属于有序查找。<br><strong>注意</strong>：对于表长较大，而关键字分布又比较均匀的查找表来说，插值查找算法的平均性能比折半查找要好的多。反之，数组中如果分布非常不均匀，那么插值查找未必是很合适的选择。<br><strong>复杂度分析</strong>：查找成功或者失败的时间复杂度均为O(log2(log2n))。</p>
<pre class=" language-python"><code class="language-python"><span class="token comment" spellcheck="true"># 插值查找算法</span>
<span class="token comment" spellcheck="true"># 时间复杂度O(log(n))</span>
<span class="token keyword">def</span> <span class="token function">binary_search</span><span class="token punctuation">(</span>lis<span class="token punctuation">,</span> key<span class="token punctuation">)</span><span class="token punctuation">:</span>
    low <span class="token operator">=</span> <span class="token number">0</span>
    high <span class="token operator">=</span> len<span class="token punctuation">(</span>lis<span class="token punctuation">)</span> <span class="token operator">-</span> <span class="token number">1</span>
    time <span class="token operator">=</span> <span class="token number">0</span>
    <span class="token keyword">while</span> low <span class="token operator">&lt;=</span> high<span class="token punctuation">:</span>
        time <span class="token operator">+=</span> <span class="token number">1</span>
        <span class="token comment" spellcheck="true"># 计算mid值是插值算法的核心代码</span>
        mid <span class="token operator">=</span> low <span class="token operator">+</span> int<span class="token punctuation">(</span><span class="token punctuation">(</span>high <span class="token operator">-</span> low<span class="token punctuation">)</span> <span class="token operator">*</span> <span class="token punctuation">(</span>key <span class="token operator">-</span> lis<span class="token punctuation">[</span>low<span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">/</span><span class="token punctuation">(</span>lis<span class="token punctuation">[</span>high<span class="token punctuation">]</span> <span class="token operator">-</span> lis<span class="token punctuation">[</span>low<span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
        <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"mid=%s, low=%s, high=%s"</span> <span class="token operator">%</span> <span class="token punctuation">(</span>mid<span class="token punctuation">,</span> low<span class="token punctuation">,</span> high<span class="token punctuation">)</span><span class="token punctuation">)</span>
        <span class="token keyword">if</span> key <span class="token operator">&lt;</span> lis<span class="token punctuation">[</span>mid<span class="token punctuation">]</span><span class="token punctuation">:</span>
            high <span class="token operator">=</span> mid <span class="token operator">-</span> <span class="token number">1</span>
        <span class="token keyword">elif</span> key <span class="token operator">></span> lis<span class="token punctuation">[</span>mid<span class="token punctuation">]</span><span class="token punctuation">:</span>
            low <span class="token operator">=</span> mid <span class="token operator">+</span> <span class="token number">1</span>
        <span class="token keyword">else</span><span class="token punctuation">:</span>
            <span class="token comment" spellcheck="true"># 打印查找的次数</span>
            <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"times: %s"</span> <span class="token operator">%</span> time<span class="token punctuation">)</span>
            <span class="token keyword">return</span> mid
    <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"times: %s"</span> <span class="token operator">%</span> time<span class="token punctuation">)</span>
    <span class="token keyword">return</span> <span class="token operator">-</span><span class="token number">1</span>
<span class="token keyword">if</span> __name__ <span class="token operator">==</span> <span class="token string">'__main__'</span><span class="token punctuation">:</span>
    LIST <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">,</span> <span class="token number">7</span><span class="token punctuation">,</span> <span class="token number">8</span><span class="token punctuation">,</span> <span class="token number">22</span><span class="token punctuation">,</span> <span class="token number">54</span><span class="token punctuation">,</span> <span class="token number">99</span><span class="token punctuation">,</span> <span class="token number">123</span><span class="token punctuation">,</span> <span class="token number">200</span><span class="token punctuation">,</span> <span class="token number">222</span><span class="token punctuation">,</span> <span class="token number">444</span><span class="token punctuation">]</span>
    result <span class="token operator">=</span> binary_search<span class="token punctuation">(</span>LIST<span class="token punctuation">,</span> <span class="token number">444</span><span class="token punctuation">)</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span>result<span class="token punctuation">)</span></code></pre>
<h3 id="五、分块查找"><a href="#五、分块查找" class="headerlink" title="五、分块查找"></a>五、分块查找</h3><p>分块查找是结合二分查找和顺序查找的一种改进方法。在分块查找里有索引表和分块的概念。<br>索引表就是帮助分块查找的一个分块依据，其实就是一个数组，用来存储每块的最大存储值，也就是范围上限；分块就是通过索引表把数据分为几块。<br><strong>基本思想：</strong><br>（1）把表长为n的线性表分成m块，前m-1块记录个数为t=n/m，第m块的记录个数小于等于t；<br>（2）在每一块中，结点的存放不一定有序，但块与块之间必须是分块有序的；<br>（3）为实现分块检索，还需建立一个索引表。索引表的每个元素对应一个块，其中<strong>包括该块内最大关键字值和块中第一个记录位置的指针。</strong></p>
<p>在每需要增加一个元素的时候，我们就需要首先根据索引表，知道这个数据应该在哪一块，然后直接把这个数据加到相应的块里面，而块内的元素之间本身不需要有序。因为块内无须有序，所以分块查找特别适合元素经常动态变化的情况。</p>
<p>分块查找只需要索引表有序，当索引表比较大的时候，可以对索引表进行二分查找，锁定块的位置，然后对块内的元素使用顺序查找。这样的总体性能虽然不会比二分查找好，却比顺序查找好很多，最重要的是不需要数列完全有序。</p>
<p><strong>分块有序表的索引存储表示</strong><br><img src="https://cdn.jsdelivr.net/gh/shw2018/cdn@1.0/sakura/img/loader/orange.progress-bar-stripe-loader.svg" data-original="/medias/img/sjjg/2085084137.png" alt=" "></p>
<pre class=" language-c"><code class="language-c"><span class="token macro property">#<span class="token directive keyword">include</span><span class="token string">&lt;stdio.h></span></span>
<span class="token macro property">#<span class="token directive keyword">define</span> MAXL 100  </span><span class="token comment" spellcheck="true">//数据表的最大长度</span>
<span class="token macro property">#<span class="token directive keyword">define</span> MAXI 20   </span><span class="token comment" spellcheck="true">//索引表的最大长度</span>

<span class="token keyword">typedef</span> <span class="token keyword">int</span> keyType<span class="token punctuation">;</span>
<span class="token keyword">typedef</span> <span class="token keyword">char</span> infoType<span class="token punctuation">[</span><span class="token number">10</span><span class="token punctuation">]</span><span class="token punctuation">;</span>

<span class="token keyword">typedef</span> <span class="token keyword">struct</span>
<span class="token punctuation">{</span>
    keyType key<span class="token punctuation">;</span> <span class="token comment" spellcheck="true">//KeyType为关键字的数据类型</span>
    infoType data<span class="token punctuation">;</span>  <span class="token comment" spellcheck="true">//其他数据</span>
<span class="token punctuation">}</span>nodeType<span class="token punctuation">;</span>

<span class="token keyword">typedef</span> <span class="token keyword">struct</span>
<span class="token punctuation">{</span>
    keyType key<span class="token punctuation">;</span>
    <span class="token keyword">int</span> link<span class="token punctuation">;</span>  <span class="token comment" spellcheck="true">//指向对应块的起始下标</span>
<span class="token punctuation">}</span>IdxType<span class="token punctuation">;</span>


<span class="token keyword">typedef</span> IdxType IDX<span class="token punctuation">[</span>MAXI<span class="token punctuation">]</span><span class="token punctuation">;</span>  <span class="token comment" spellcheck="true">//索引表类型</span>
<span class="token keyword">typedef</span> nodeType seqList<span class="token punctuation">[</span>MAXL<span class="token punctuation">]</span><span class="token punctuation">;</span>  <span class="token comment" spellcheck="true">//顺序表类型</span>


<span class="token keyword">int</span> <span class="token function">IdxSearch</span><span class="token punctuation">(</span>IDX I<span class="token punctuation">,</span> <span class="token keyword">int</span> m<span class="token punctuation">,</span> seqList R<span class="token punctuation">,</span> <span class="token keyword">int</span> n<span class="token punctuation">,</span> keyType k<span class="token punctuation">)</span>
<span class="token punctuation">{</span>   <span class="token comment" spellcheck="true">// 共n个元素,   m块</span>
    <span class="token keyword">int</span> low<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">,</span> high<span class="token operator">=</span>m<span class="token number">-1</span><span class="token punctuation">,</span> mid<span class="token punctuation">,</span> i<span class="token punctuation">;</span>
    <span class="token keyword">int</span> b<span class="token operator">=</span> n<span class="token operator">/</span>m<span class="token punctuation">;</span>  <span class="token comment" spellcheck="true">//b为每块的记录个数</span>

    <span class="token keyword">while</span><span class="token punctuation">(</span>low<span class="token operator">&lt;=</span>high<span class="token punctuation">)</span> <span class="token comment" spellcheck="true">//在索引表中进行二分查找,找到的位置存放在low中</span>
    <span class="token punctuation">{</span>
        mid <span class="token operator">=</span> <span class="token punctuation">(</span>low<span class="token operator">+</span>high<span class="token punctuation">)</span><span class="token operator">/</span><span class="token number">2</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span><span class="token punctuation">(</span>I<span class="token punctuation">[</span>mid<span class="token punctuation">]</span><span class="token punctuation">.</span>key <span class="token operator">>=</span> k<span class="token punctuation">)</span>
            high <span class="token operator">=</span> mid<span class="token number">-1</span><span class="token punctuation">;</span>
        <span class="token keyword">else</span>
            low <span class="token operator">=</span> mid<span class="token operator">+</span><span class="token number">1</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment" spellcheck="true">//应在索引表的high+1块中,再在线性表中进行顺序查找</span>
    i <span class="token operator">=</span> I<span class="token punctuation">[</span>high<span class="token operator">+</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">.</span>link<span class="token punctuation">;</span>    <span class="token comment" spellcheck="true">//分块中的起始下标</span>
    <span class="token keyword">while</span><span class="token punctuation">(</span>i<span class="token operator">&lt;=</span>I<span class="token punctuation">[</span>high<span class="token operator">+</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">.</span>link<span class="token operator">+</span>b<span class="token number">-1</span> <span class="token operator">&amp;&amp;</span> R<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">.</span>key <span class="token operator">!=</span> k<span class="token punctuation">)</span>    <span class="token comment" spellcheck="true">//I[high+1].link+b-1  块长度</span>
        i<span class="token operator">++</span><span class="token punctuation">;</span>

    <span class="token keyword">if</span><span class="token punctuation">(</span>i<span class="token operator">&lt;=</span>I<span class="token punctuation">[</span>high<span class="token operator">+</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">.</span>link<span class="token operator">+</span>b<span class="token number">-1</span><span class="token punctuation">)</span>
        <span class="token keyword">return</span> i<span class="token operator">+</span><span class="token number">1</span><span class="token punctuation">;</span>
    <span class="token keyword">else</span>
        <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token keyword">int</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">{</span>
    <span class="token keyword">int</span> i<span class="token punctuation">,</span>n<span class="token operator">=</span><span class="token number">25</span><span class="token punctuation">,</span>m<span class="token operator">=</span><span class="token number">5</span><span class="token punctuation">,</span>j<span class="token punctuation">;</span>
    seqList R<span class="token punctuation">;</span>
    IDX I<span class="token operator">=</span> <span class="token punctuation">{</span><span class="token punctuation">{</span><span class="token number">14</span><span class="token punctuation">,</span><span class="token number">0</span><span class="token punctuation">}</span><span class="token punctuation">,</span><span class="token punctuation">{</span><span class="token number">34</span><span class="token punctuation">,</span><span class="token number">5</span><span class="token punctuation">}</span><span class="token punctuation">,</span><span class="token punctuation">{</span><span class="token number">66</span><span class="token punctuation">,</span><span class="token number">10</span><span class="token punctuation">}</span><span class="token punctuation">,</span><span class="token punctuation">{</span><span class="token number">85</span><span class="token punctuation">,</span><span class="token number">15</span><span class="token punctuation">}</span><span class="token punctuation">,</span><span class="token punctuation">{</span><span class="token number">100</span><span class="token punctuation">,</span><span class="token number">20</span><span class="token punctuation">}</span><span class="token punctuation">}</span><span class="token punctuation">;</span>
    keyType a<span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token operator">=</span> <span class="token punctuation">{</span><span class="token number">8</span><span class="token punctuation">,</span><span class="token number">14</span><span class="token punctuation">,</span><span class="token number">6</span><span class="token punctuation">,</span><span class="token number">9</span><span class="token punctuation">,</span><span class="token number">10</span><span class="token punctuation">,</span><span class="token number">22</span><span class="token punctuation">,</span><span class="token number">34</span><span class="token punctuation">,</span><span class="token number">18</span><span class="token punctuation">,</span><span class="token number">19</span><span class="token punctuation">,</span><span class="token number">31</span><span class="token punctuation">,</span><span class="token number">40</span><span class="token punctuation">,</span><span class="token number">38</span><span class="token punctuation">,</span><span class="token number">54</span><span class="token punctuation">,</span><span class="token number">66</span><span class="token punctuation">,</span><span class="token number">46</span><span class="token punctuation">,</span><span class="token number">71</span><span class="token punctuation">,</span><span class="token number">78</span><span class="token punctuation">,</span><span class="token number">68</span><span class="token punctuation">,</span><span class="token number">80</span><span class="token punctuation">,</span><span class="token number">85</span><span class="token punctuation">,</span><span class="token number">100</span><span class="token punctuation">,</span><span class="token number">94</span><span class="token punctuation">,</span><span class="token number">88</span><span class="token punctuation">,</span><span class="token number">96</span><span class="token punctuation">,</span><span class="token number">87</span><span class="token punctuation">}</span><span class="token punctuation">;</span>
    keyType x<span class="token operator">=</span><span class="token number">85</span><span class="token punctuation">;</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span>i<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">;</span> i<span class="token operator">&lt;</span>n<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span>
        R<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">.</span>key<span class="token operator">=</span>a<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">;</span>
    j<span class="token operator">=</span><span class="token function">IdxSearch</span><span class="token punctuation">(</span>I<span class="token punctuation">,</span>m<span class="token punctuation">,</span>R<span class="token punctuation">,</span>n<span class="token punctuation">,</span>x<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>j<span class="token operator">!=</span><span class="token number">0</span><span class="token punctuation">)</span>
        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"%d是第%d个数据\n"</span><span class="token punctuation">,</span>x<span class="token punctuation">,</span>j<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">else</span>
        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"未找到%d\n"</span><span class="token punctuation">,</span>x<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span> </code></pre>
<p><strong>索引顺序表＝索引＋顺序表</strong><br>一般情况下，索引为有序表。 分块查找步骤：<br>1）由索引确定记录所在区间；<br>2）在顺序表的某个区间内进行顺序查找。<br>可见，索引顺序查找的过程也是一个“缩小区间”的查找过程。</p>
<p><strong>分块查找性能分析</strong></p>
<blockquote>
<p>分块查找的ASL=查找“索引”的ASL+查找“顺序表”的ASL</p>
</blockquote>
<p>设n个数据元素的查找表分为m个子表，且每个子表均为t个元素，即：m*t=n<br>设在索引表上的检索也采用顺序查找，这样，分块查找的平均查找长度为：<br><img src="https://cdn.jsdelivr.net/gh/shw2018/cdn@1.0/sakura/img/loader/orange.progress-bar-stripe-loader.svg" data-original="/medias/img/sjjg/1145205369.png" alt=" "></p>
<h3 id="顺序表静态查找方法的比较"><a href="#顺序表静态查找方法的比较" class="headerlink" title="顺序表静态查找方法的比较"></a>顺序表静态查找方法的比较</h3><p>在上述3种查找方法中</p>
<ul>
<li><strong>二分查找</strong>具有最高的查找效率，但要求必须是顺序存储结构且元素有序排列，且若要进行插入、删除运算时，因需移动大量元素，运行效率将降低，所以二分查找只适用于有序表的静态查找；</li>
<li><strong>顺序查找</strong>效率最低，但对线性表无任何要求——顺序存储或链式存储都可，是否有序都无影响；</li>
<li><strong>分块查找</strong>是顺序查找和二分查找的综合。</li>
</ul>

            </div>
            <hr/>

            
            <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.88rem;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-large waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fa fa-close"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力!</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.bmp" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.bmp" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>
            

            <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    <div class="social-share" data-disabled="qzone" data-wechat-qrcode-helper="<p>微信里点“发现”->“扫一扫”二维码便可查看分享。</p>"></div>
    
</div>

<script src="/libs/share/js/social-share.min.js"></script>

            
            
            
            <div class="reprint1">
                <p>
                    <span class="reprint1-tip">
                        <i class="fa fa-exclamation-circle"></i>&nbsp;&nbsp;转载请注明:
                    </span>
                    <a href="http://leehaisen.gitee.io" class="b-link-green">hisen</a>
                    <i class="fa fa-angle-right fa-lg fa-fw text-color"></i>
                    <a href="/2019/02/14/shu-ju-jie-gou-yu-suan-fa-13-cha-zhao/" class="b-link-green">数据结构与算法13—查找</a>
                </p>
            </div>

        </div>
    </div>

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fa fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2019/02/15/shu-ju-jie-gou-yu-suan-fa-14-er-cha-pai-xu-cha-zhao-shu/">
                    <div class="card-image">
                        
                        <img src="/medias/banner/7.jpg" class="responsive-img" alt="数据结构与算法14—二叉排序(查找)树">
                        
                        <span class="card-title">数据结构与算法14—二叉排序(查找)树</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            叉排序(查找)树的数据结构与使用方式
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="fa fa-clock-o fa-fw icon-date"></i>2019-02-15
                        </span>
                        <span class="publish-author">
                            
                            <i class="fa fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/数据结构/" class="post-category" target="_blank">
                                    数据结构
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/数据结构/" target="_blank">
                        <span class="chip bg-color">数据结构</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fa fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2019/02/13/shu-ju-jie-gou-yu-suan-fa-12-zui-duan-lu-jing/">
                    <div class="card-image">
                        
                        <img src="/medias/banner/9.jpg" class="responsive-img" alt="数据结构与算法12—最短路径">
                        
                        <span class="card-title">数据结构与算法12—最短路径</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            最短路径
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="fa fa-clock-o fa-fw icon-date"></i>2019-02-13
                            </span>
                        <span class="publish-author">
                            
                            <i class="fa fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/数据结构/" class="post-category" target="_blank">
                                    数据结构
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/数据结构/" target="_blank">
                        <span class="chip bg-color">数据结构</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>
</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('80')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: hisen<br />'
            + '作者: hisen<br />'
            + '链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="fa fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fa fa-list"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            // headingsOffset: -205,
            headingSelector: 'h1, h2, h3, h4, h5'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h1, h2, h3, h4, h5').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).slideUp(500);
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).slideDown(500);
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>
    

</main>


        <footer class="page-footer bg-color">
    <div class="container row center-align">
        <div class="col s12 m8 l8 copy-right">
            Copyright&copy; 2019 Hisen. 

            <br>
            <span id="sitetime"></span><span class="my-face">ღゝ◡╹)ノ♡</span>
            <br>

            

            
                    
                        <span id="busuanzi_container_site_pv" style='display:none'></span>
                        总访问量: <span id="busuanzi_value_site_pv" class="white-color"></span>
                    
        
                    
                        <span id="busuanzi_container_site_uv" style='display:none'></span>
                        人次&nbsp; | &nbsp;访客人数: <span id="busuanzi_value_site_uv" class="white-color"></span> 人
                    
    
            

            
                &nbsp; | &nbsp;字数统计:&nbsp;
                <span class="white-color">52.9k</span> 字
            

            
            <br>

        </div>

        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/Ylisen10" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fa fa-github"></i>
    </a>


 
    <a href="https://mail.qq.com/cgi-bin/qm_share?t=qm_mailme&email=1308917676@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fa fa-envelope-open"></i>
    </a>




    <a href="https://zhihu.com/people/亦小海" class="tooltipped" target="_blank" data-tooltip="访问我的知乎" data-position="top" data-delay="50">
        <i class="fa fa-inverse">知</i>
    </a>



    <a href="http://wpa.qq.com/msgrd?v=3&uin=1308917676&site=qq&menu=yes" class="tooltipped" target="_blank" data-tooltip="访问我的QQ空间" data-position="top" data-delay="50">
        <i class="fa fa-qq"></i>
    </a>





    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fa fa-rss"></i>
    </a>
</div>

    </div>
</footer>

<div class="progress-bar"></div>

<script language=javascript>
    function siteTime() {
        window.setTimeout("siteTime()", 1000);
        var seconds = 1000;
        var minutes = seconds * 60;
        var hours = minutes * 60;
        var days = hours * 24;
        var years = days * 365;
        var today = new Date();
        var todayYear = today.getFullYear();
        var todayMonth = today.getMonth() + 1;
        var todayDate = today.getDate();
        var todayHour = today.getHours();
        var todayMinute = today.getMinutes();
        var todaySecond = today.getSeconds();

        /* Date.UTC() -- 返回date对象距世界标准时间(UTC)1970年1月1日午夜之间的毫秒数(时间戳)
        year - 作为date对象的年份，为4位年份值
        month - 0-11之间的整数，做为date对象的月份
        day - 1-31之间的整数，做为date对象的天数
        hours - 0(午夜24点)-23之间的整数，做为date对象的小时数
        minutes - 0-59之间的整数，做为date对象的分钟数
        seconds - 0-59之间的整数，做为date对象的秒数
        microseconds - 0-999之间的整数，做为date对象的毫秒数 */

        var t1 = Date.UTC(2019, 08, 10, 00, 00, 00); //北京时间2019-8-1 00:00:00
        var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
        var diff = t2 - t1;
        var diffYears = Math.floor(diff / years);
        var diffDays = Math.floor((diff / days) - diffYears * 365);
        var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
        var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) / minutes);
        var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours - diffMinutes *
            minutes) / seconds);
        document.getElementById("sitetime").innerHTML = "本站已勉强运行 " + diffYears + " 年 " + diffDays + " 天 " + diffHours +
            " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒" ;
    } /*因为建站时间还没有一年，就将之注释掉了。需要的可以取消*/
    siteTime();
</script>






        <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fa fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/" + "search.xml", 'searchInput', 'searchResult');
});
</script>
        <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fa fa-angle-up"></i>
    </a>
</div>


        <script src="https://cdn.bootcss.com/materialize/1.0.0/js/materialize.min.js"></script>
        <script src="https://cdn.bootcss.com/masonry/4.2.2/masonry.pkgd.min.js"></script>
        <script src="https://cdn.bootcss.com/aos/3.0.0-beta.6/aos.js"></script>
        <script src="https://cdn.bootcss.com/scrollprogress/3.0.2/scrollProgress.min.js"></script>
        <script src="https://cdn.bootcss.com/lightgallery/1.6.12/js/lightgallery-all.min.js"></script>
        <script src="/js/matery.js"></script>

        <!-- Global site tag (gtag.js) - Google Analytics -->



        
            <script src="/libs/others/clicklove.js"></script>
        

        
            <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
        

        <!-- 洪卫 shw2018 add 2019.08.28 -->
<!--         <script type="text/javascript">
            var OriginTitile = document.title,
                st;
            document.addEventListener("visibilitychange", function () {
                document.hidden ? (document.title = "看不见我🙈~看不见我🙈~", clearTimeout(st)) : (document.title =
                    "(๑•̀ㅂ•́) ✧被发现了～", st = setTimeout(function () {
                        document.title = OriginTitile
                    }, 3e3))
            })
        </script> -->

        <!-- 鼠标点击烟花爆炸效果  洪卫 shw2018 add 2019.09.09 -->
        

        <!-- 背景雪花飘落特效洪卫 shw2018 add 2019.09.10 -->
        

        <!-- 鼠标点击文字特效 洪卫 shw2018 add 2019.09.10-->
        

        <!-- 背景雪花飘落特效 洪卫 shw2018 add 2019.09.10 -->
        

        <!-- 在线聊天工具  洪卫 shw2018 add 2019.09.11 -->
        
            <script src="//code.tidio.co/xxxxxxxxxxxxxxxxxxxxxxxxxxx.js"></script>
            <!--  在线聊天位置自定义  洪卫 shw2018 add 2019.09.13  -->
            <script> 
                $(document).ready(function () {

                    setInterval(change_Tidio, 50);  
                    function change_Tidio() { 

                        var tidio=$("#tidio-chat iframe");
                        if(tidio.css("display")=="block"&& $(window).width()>977 ){
                            document.getElementById("tidio-chat-iframe").style.bottom= ($("div#backTop.top-scroll").css("display")=="none" &&$(window).width()>977)>0? "-40px" : ($("div.toc-title").length&&$(window).width()>977)>0?"80px":"20px";   
                            document.getElementById("tidio-chat-iframe").style.right="-15px";   
                            document.getElementById("tidio-chat-iframe").style.height=parseInt(tidio.css("height"))>=520?"520px":tidio.css("height");
                            document.getElementById("tidio-chat-iframe").style.zIndex="997";
                        } 
                        else if(tidio.css("display")=="block"&&$(window).width()>601 &&$(window).width()<992 ){
                            document.getElementById("tidio-chat-iframe").style.bottom= ($("div#backTop.top-scroll").css("display")=="none" && 601< $(window).width()<992)>0? "-40px":"20px" ;   
                            document.getElementById("tidio-chat-iframe").style.right="-15px"; 
                            document.getElementById("tidio-chat-iframe").style.zIndex="997";
                        }
                        else if(tidio.css("display")=="block"&&$(window).width()<601 && parseInt(tidio.css("height"))<230){
                            document.getElementById("tidio-chat-iframe").style.bottom= ($("div#backTop.top-scroll").css("display")=="none" && $(window).width()<601)>0? "-10px":"45px" ;   
                            document.getElementById("tidio-chat-iframe").style.zIndex="997";
                        }

                        if( tidio.css("display")=="block"&&$(window).width()<601 && parseInt(tidio.css("height"))>=230){
                            document.getElementById("tidio-chat-iframe").style.zIndex="998";
                        }
                    } 
                }); 
            </script>
        

        <!-- 背景 canvas-nest  洪卫 shw 2018  add 2019.09.15-->
        

        <!-- 背景静止彩带  洪卫 shw 2018  add 2019.09.15-->
        

        <!-- 背景动态彩带 洪卫 shw 2018  add 2019.09.15-->
        

    <script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"log":false,"model":{"jsonPath":"/live2dw/assets/wanko.model.json"},"display":{"position":"left","width":150,"height":200},"mobile":{"show":false},"react":{"opacity":0.7}});</script><script>!function(e){var r=Array.prototype.slice.call(document.querySelectorAll("img[data-original]"));function t(){for(var c=0;c<r.length;c++)t=r[c],void 0,0<=(n=t.getBoundingClientRect()).top&&0<=n.left&&n.top<=(e.innerHeight||document.documentElement.clientHeight)&&function(){var t,n,e,i,o=r[c];t=o,n=function(){r=r.filter(function(t){return o!==t})},e=new Image,i=t.getAttribute("data-original"),e.onload=function(){t.src=i,n&&n()},e.src=i}();var t,n}t(),e.addEventListener("scroll",function(){!function(t,n){clearTimeout(t.tId),t.tId=setTimeout(function(){t.call(n)},500)}(t,e)})}(this);</script></body>
</html>